﻿using System;

using Builderator.Core.Plugin;
using Builderator.Core.Trigger;
using Builderator.Core.Interfaces;

namespace Builderator.Core.Action
{
    public class IntervalTrigger : TriggerBase, ITrigger
    {
        [DocumentProperty("Interval", typeof(TimeInterval), false)]
        public TimeInterval Interval
        {
            get;
            set;
        }

        private IntervalTimer intervalTimer;

        public IntervalTrigger()
            : base("Interval", new Guid("60AE048E-EAEB-11E0-B9D2-C5BC4824019B"))
        {

        }

        private bool SetupTimer()
        {
            double pause;

            pause = this.Interval.seconds;

            pause += (this.Interval.minutes * 60);

            pause += (this.Interval.hours * 3600);

            pause *= 1000;

            if (pause == 0)
                return false;

            this.intervalTimer = new IntervalTimer(pause, new IntervalTimer.Trigger(this.TriggerBuildHandler));

            return true;
        }

        private void TriggerBuildHandler()
        {
            this.TriggerBuild();

            this.intervalTimer.Restart();
        }

        public override void Start()
        {
            if (!this.SetupTimer())
                return;

            this.intervalTimer.Start();
        }

        public override void Stop()
        {
            this.intervalTimer.Stop();
        }
    }
}